<template>
  <div class="el-form">
    <slot></slot>
    <button @click="handleFormValidate">校验</button>
  </div>
</template>
<script lang="ts">
import emitt from "emitt";
const emitter: mitt.Emitter = emitt();
export default {
  name: "ElForm",
};
</script>
<script setup lang="ts">
import {
  computed,
  withDefaults,
  provide,
  onMounted,
  onUnmounted,
  onBeforeMount,
  getCurrentInstance,
} from "vue";
interface RuleItem {
  required?: true | false;
  message?: string;
  trigger?: string;
}
type PropModel = { [key: string]: any };
type PropRules = {
  [key: keyof PropModel]: RuleItem;
};
interface Props {
  model?: PropModel;
  rules?: PropRules;
}
function handleFormValidate(cb: (isValid: boolean) => void) {
  const tasks = subChildrens.map((validate) => validate());
  Promise.all(tasks)
    .then(() => {
      cb(true);
    })
    .catch(() => {
      cb(false);
    });
}
const props = withDefaults(defineProps<Props>(), {
  model: {},
  rules: [],
});
provide("formEmitter", emitter);
provide("formData", props);
const subChildrens = [];
const handleSubMounted = (item) => {
  subChildrens.push(item);
  console.log(subChildrens);
};
emitter.on("itemMounted", handleSubMounted);
onUnmounted(() => {
  emitter.off("itemMounted", handleSubMounted);
});
</script>
<style lang="scss">
@import "../../styles/mixin";
@include b(form) {
  display: inline-block;
}
</style>
